package com.cs.paoyer.common.util;



import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.DataHandler;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.AddressException;
import javax.mail.BodyPart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;
import com.cs.paoyer.common.exception.SystemException;
import com.cs.paoyer.common.exception.CommonSystemException;

/**
 * Encargada de enviar mensajes de correo electronico, dados una serie de
 * par�metros.
 *
 * Para que esta clase funcione correctamente se necesita una imagen, banner_etb.gif,
 * en el directorio de la aplicacion.
 *
 * @version 1.0
 */
public class EmailSender {

  // Directorio por defecto de la aplicaci�n.
  private static String SAAW_DIR = "";

  /**
   * Env�a un mensaje de correo con los datos de uhuna excepci�n de sistema
   * registrada en la aplicaci�n.
   *
   * @param exception
   * @throws MessagingException
   * @throws SystemException
   */
  public static void postExceptionMail(SystemException exception)
      throws MessagingException, SystemException {

    String mailHost = null;
    try {

      PropertiesLoader propertiesLoader = PropertiesLoader.getInstance();

      mailHost = propertiesLoader.getProperty("MAIL_HOST");
      String mailFrom = propertiesLoader.getProperty("MAIL_FROM");
      String adminMail = propertiesLoader.getProperty("EXCEPTION_ADMIN_MAIL");
      SAAW_DIR = propertiesLoader.getProperty("SAAW_DIR");

      //Extrae datos adjuntos.
      String additionalExceptionData = exception.getCustomMessage();
      //Nombre de la excepci�n de Java
      String javaExceptionName = "";
      //StackTrace de la excepci�n de Java
      String javaExceptionStackTrace = "";
      String[] to = new String[1];

      to[0] = adminMail;

      //Extrae la informaci�n de la Excepci�n de Java acompa�ante.
      if (exception.getJavaException() != null) {
        javaExceptionName = exception.getJavaException().getClass().getName();
        javaExceptionStackTrace = exception.getJavaStackTrace();
      }

      String subject = "Excepci�n: " + exception.getExceptionVO().getId();

      //Aplica el formato de mail a los datos.
      String message = "" +
        "<tr bgcolor=\"#f7f7e7\">" +
        "<td align=\"left\"><font size=\"4\">Excepci&oacute;n:</font></td>" +
        "<td align=\"left\"><font size=\"3\">"+ exception.getExceptionVO().getMessage() + "<br>" +
        "</font></td>" +
        "</tr>";

      message = message +
        "<tr>" +
        "<td align=\"left\"><font size=\"4\">Informaci&oacute;n Adicional de la excepci&oacute;n: </font></td>" +
        "<td align=\"left\"><font size=\"3\">" + exception.getExceptionVO().getDetail() + "<br>" +
        additionalExceptionData + "</font></td>" +
        "</tr>";

      message = message +
        "<tr bgcolor=\"#f7f7e7\">" +
        "<td align=\"left\"><font size=\"4\">Excepci&oacute;n de Java Asociada: </font></td>" +
        "<td align=\"left\"><font size=\"3\">" + javaExceptionStackTrace +
        "</font></td>" +
        "</tr>";

      postMail(to, subject, message, mailFrom, mailHost);
    } catch (SystemException ex) {
      throw new SystemException( new CommonSystemException().getModuleVO(),
                                 CommonSystemException.PROPERTY_NOT_FOUND, ex,
                                 "Desde EmailSender - postExceptionMail", false );
    }


  }



  /**
   * Envia un correo electronico
   * @param recipients[]    Arreglo con el E-mail de quienes reciben el mensaje
   * @param subject         Obejto del mensaje
   * @param message         Contenido del email
   * @param MailFrom        Direcci�n electr�nica del remitente
   * @param MailHost        Servidor STMP de correo de salida de los emails
   * */
  public static void postMail(String recipients[],
                              String subject,
                              String messageBody,
                              String MailFrom,
                              String MailHost)
      throws AddressException, MessagingException {

    boolean           debug = false;
    Properties        props = new Properties();
    Session           session = null;
    Message           message = null;
    InternetAddress   addressFrom  = null;
    InternetAddress[] addressToSet = null;
    String htmlText1;
    String htmlText3;

    //Set the host smtp address
    props.put("mail.host", MailHost);
    props.put("mail.from", MailFrom);

    // create some properties and get the default Session
    session = Session.getDefaultInstance(props, null);
    session.setDebug(debug);

    // create a message
    message = new MimeMessage(session);

    // set the from and to address

    addressFrom = new InternetAddress(MailFrom);

    message.setFrom(addressFrom);

    addressToSet = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
      try {
        addressToSet[i] = new InternetAddress(recipients[i]);
      } catch (AddressException ex2) {
      }
    }
    message.setRecipients(Message.RecipientType.TO, addressToSet);

    // Especifica el Asunto del mensaje.
    message.setSubject(subject);

   // Create your new message part
    BodyPart messageBodyPart = new MimeBodyPart();

    // Set the HTML content, be sure it references the attachment
    htmlText1 = "<html>" +
      "<body>"+
      "<table width=\"100%\"  border=\"0\" cellspacing=\"0\" cellpadding=\"0\">" +
      "<tr>" +
      "<td><table width=\"100%\"  border=\"0\" cellspacing=\"2\" cellpadding=\"0\">" +
        "<tr>" +
          "<td colspan=\"2\" align=\"center\"><img src=\"cid:memememe\"></td>" +
        "</tr>" +
        "<tr>" +
          "<td colspan=\"2\" align=\"center\"><font  color=\"#FF0000\" size=\"3\"> Mensaje de Excepci&oacute;n de Saaw </font></td>" +
        "</tr>";

    htmlText3 = "</table></td>" +
        "</tr>" +
       "</table>" +
      "</body>" +
      "</html>";

    // Set the content of the body part
    messageBodyPart.setContent(htmlText1 + messageBody + htmlText3, "text/html");

    // Create a related multi-part to combine the parts
    MimeMultipart multipart = new MimeMultipart("related");

    // Add body part to multipart
    multipart.addBodyPart(messageBodyPart);

    // Create part for the image
    messageBodyPart = new MimeBodyPart();

    // Fetch the image and associate to part
    String file = SAAW_DIR + "\\images\\banner_etb.gif";
    DataSource fds = new FileDataSource(file);
    messageBodyPart.setDataHandler(new DataHandler(fds));

    // Add a header to connect to the HTML
    messageBodyPart.setHeader("Content-ID","<memememe>");

    // Add part to multi-part
    multipart.addBodyPart(messageBodyPart);

    // Associate multi-part with message
    message.setContent(multipart);

    // Send message
    Transport.send(message);

  }

  public static void main(String[] args) {
    throw new SystemException( new CommonSystemException().getModuleVO(),
                                 CommonSystemException.DATE_PARSE_EXCEPTION, null,
                                 "Desde EmailSender - postExceptionMail");
  }

}
